package com.itfreer.file;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Map;

import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.stereotype.Component;

import com.itfreer.file.service.IObjectUploadService;

/**
 * 定义对象上传接口
 */
@Component
public class PathObjectUpload extends ObjectBase implements IObjectUploadService, BeanFactoryAware {

	/**
	 * 创建文件夹
	 * 多级目录创建最后一级即可，比如dir1/dir2/dir3/，创建dir1/dir2/dir3/即可，dir1/、dir1/dir2/不需要创建
	 * 
	 * @param bucketName
	 *            存储块名称
	 * @param objectName
	 *            文件夹名称
	 */
	public void createDir(String bucketName, String objectName) {
		String path = getBasePath();
		if (!objectName.endsWith("/")) {
			objectName += "/";
		}
		if (path.endsWith("/")) {
			path += bucketName + "/";
		} else {
			path += "/" + bucketName + "/";
		}
		path += objectName;

		File fileinfo = new File(path);
		if (!fileinfo.isDirectory()) {
			fileinfo.mkdirs();
		}
	}

	/**
	 * 上传文件流
	 * 
	 * @param bucketName
	 *            存储块名称
	 * @param objectKey
	 *            对象存储key
	 * @param content
	 *            对象流
	 * @param meta
	 *            对象元数据
	 * @return 文件是否上传成功
	 */
	public boolean putObject(String bucketName, String objectKey, byte[] content, Map<String, String> meta) {
		String fileName = getBasePath();
		if (fileName.endsWith("/")) {
			fileName += bucketName + "/";
		} else {
			fileName += "/" + bucketName + "/";
		}
		fileName += objectKey;
		try {
			FileOutputStream file = new FileOutputStream(fileName);
			file.write(content);
			file.close();
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 断点续传上传
	 * 
	 * @param bucketName
	 *            存储块名称
	 * @param objectKey
	 *            对象存储key
	 * @param part
	 *            文件块
	 * @param meta
	 *            对象元数据
	 */
	public boolean uploadFile(String bucketName, String objectKey, FileSegmentInfo part, Map<String, String> meta) {
		String fileName = getBasePath();
		if (fileName.endsWith("/")) {
			fileName += bucketName + "/";
		} else {
			fileName += "/" + bucketName + "/";
		}
		fileName += objectKey;
		
		try {
			RandomAccessFile fileOutputStream = new RandomAccessFile(fileName, "rwd");
			int start = part.getSegmentIndex() * part.getSegmentSize();
			fileOutputStream.seek(start);
			fileOutputStream.write(part.getSegmentContent(), 0, part.getSegmentContent().length);
			fileOutputStream.close();
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
}
